package com.puman.watchtrade.fragment.personal;

import java.text.BreakIterator;
import java.text.DecimalFormat;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.ViewById;
import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.pingplusplus.android.PaymentActivity;
import com.puman.watchtrade.MainActivity;
import com.puman.watchtrade.R;
import com.puman.watchtrade.fragment.home.GoodsDetailFragment;
import com.puman.watchtrade.fragment.personal.adapter.BiddingRecordListViewAdapter;
import com.puman.watchtrade.fragment.personal.handler.PersonalHttpHandler;
import com.puman.watchtrade.fragment.personal.model.BiddRecord;
import com.puman.watchtrade.fragment.personal.model.BiddRecords;
import com.puman.watchtrade.fragment.personal.model.Charge;
import com.puman.watchtrade.fragment.set.LoginFragment;
import com.puman.watchtrade.util.DataResult;
import com.puman.watchtrade.util.Gjfun;
import com.puman.watchtrade.util.GlobalData;
import com.puman.watchtrade.util.LoadingProgressDialog;
import com.puman.watchtrade.util.PullDownListView;
import com.umeng.socialize.location.GetLocationTask;

/*
 */
//@EFragment(R.layout.bidding_record_layout)
@SuppressLint("ValidFragment")
public class BiddingRecordFregment extends Fragment implements
		PullDownListView.OnRefreshListioner, OnClickListener {
	private View mView;

	/*
	 * init UI
	 */
	// @ViewById(R.id.bidding_record_listview)
	ListView listView;
	// @ViewById(R.id.top_title)
	TextView toptitle;
	/*
	 * init variable
	 */

	private BiddingRecordListViewAdapter biddingRecordListViewAdapter;
	private BiddRecords biddRecords = new BiddRecords();
	private BiddRecords biddRecordsTemp = new BiddRecords();
	public static final int GET_SUC = 0x1;
	public static final int GET_FAIL = 0x2;
	public static final int GET_CHARGE_SUC = 0x3;
	public static final int GET_CHARGE_FAIL = 0x4;
	private DataResult dataResult = new DataResult();
	private DataResult dataResultForZf = new DataResult();
	private PersonalHttpHandler personalHttpHandler = new PersonalHttpHandler();
	private int pageNumber = 1;
	private int pageNumberTemp = 1;
	private boolean isRefreash = false;
	/**
	 * 存储上一个选择项的Index
	 */
	private int preSelImgIndex = 0;
	// @ViewById(R.id.sreach_list)
	PullDownListView mPullDownView;
	private LoadingProgressDialog mProgress = null;
	public static int zhifuPosition = -1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}

	private String flag = "0";
	private String title = "";

	public BiddingRecordFregment() {
		this.flag = "0";
		this.title = "报价记录";
	}

	public BiddingRecordFregment(String flag, String title) {
		this.flag = flag;
		this.title = title;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		mView = inflater.inflate(R.layout.bidding_record_layout, container,
				false);
		initView();
		initData();
		Log.i("curry", "onCreateView");
//		if (savedInstanceState != null) {
//			biddRecords = (BiddRecords) savedInstanceState.getSerializable("biddRecords");
//			if (biddRecords.biddRecordList.size() == 0) {
//				Gjfun.emptyLayout(mView, "亲，您还没有参与竞拍哦", "", true);
//				mView.findViewById(R.id.sreach_list).setVisibility(
//						View.GONE);
//			} else {
//				if (biddRecords.biddRecordList.size() < 6) {
//					mPullDownView.setMore(false);
//				} else {
//					mPullDownView.setMore(true);
//				}
//				Gjfun.emptyLayout(mView, null, "", false);
//				mView.findViewById(R.id.sreach_list).setVisibility(
//						View.VISIBLE);
//			}
//
//			biddingRecordListViewAdapter.notifyDataSetChanged();
//		} else {
			getInfoList();
//		}
		return mView;
	}
	

	private void initView() {
		listView = (ListView) mView.findViewById(R.id.bidding_record_listview);
		toptitle = (TextView) mView.findViewById(R.id.top_title);
		mPullDownView = (PullDownListView) mView.findViewById(R.id.sreach_list);
		zhifuPosition = -1;

	}

	private void initData() {
		toptitle.setText(title);
		mView.findViewById(R.id.main_left_imgbtn).setOnClickListener(this);
		biddingRecordListViewAdapter = new BiddingRecordListViewAdapter(
				getActivity(), biddRecords, this, this);
		listView.setAdapter(biddingRecordListViewAdapter);

		listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
				FragmentTransaction transaction = MainActivity.fragmentManager
						.beginTransaction();
				GoodsDetailFragment goodsDetailFragment = new GoodsDetailFragment(
						biddRecords.biddRecordList.get(position - 1)
								.getGoodsNo(), biddRecords.biddRecordList.get(
								position - 1).getCompetionStatus());
				transaction.replace(R.id.main_non_bottom, goodsDetailFragment);
				transaction.addToBackStack(null);
				transaction.commit();
			}
		});

		mPullDownView.setRefreshListioner(this);
		listView = mPullDownView.mListView;
	}

	private void getInfoList() {
		mProgress = Gjfun.startProgressDialog(mProgress, getActivity());
		((MainActivity) getActivity()).cachedThreadPoolMinPriority
				.execute(infolistRunnable);
	}

	/*
	 * 
	 */
	Runnable infolistRunnable = new Runnable() {
		@Override
		public void run() {
			int what = GET_FAIL;
			dataResult = personalHttpHandler.biddingList(pageNumber + "", flag);
			if (dataResult.flag) {
				what = GET_SUC;
			}
			sendMessage(what);
		}
	};

	Callback callback = new Callback() {
		@Override
		public boolean handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
			case GET_SUC:
				Gjfun.stopProgressDialog(mProgress);
				pageNumber = pageNumberTemp;
				mPullDownView.onRefreshComplete();
				mPullDownView.onLoadMoreComplete();
				// 这里设置true表示还有更多加载，设置为false底部将不显示更多
				if (isRefreash) {
					biddRecords.biddRecordList.clear();

				}

				for (int i = 0; i < ((BiddRecords) dataResult.object).biddRecordList
						.size(); i++) {
					biddRecords.biddRecordList.add(i,
							((BiddRecords) dataResult.object).biddRecordList
									.get(i));
				}
				// biddRecords.biddRecordList.clear();
				if (biddRecords.biddRecordList.size() == 0) {
					Gjfun.emptyLayout(mView, "亲，您还没有参与竞拍哦", "", true);
					mView.findViewById(R.id.sreach_list).setVisibility(
							View.GONE);
				} else {
					if (biddRecords.biddRecordList.size() < 6) {
						mPullDownView.setMore(false);
					} else {
						mPullDownView.setMore(true);
					}
					Gjfun.emptyLayout(mView, null, "", false);
					mView.findViewById(R.id.sreach_list).setVisibility(
							View.VISIBLE);
				}

				biddingRecordListViewAdapter.notifyDataSetChanged();
				break;
			case GET_FAIL:
				Gjfun.stopProgressDialog(mProgress);
				Gjfun.emptyLayout(mView, "亲，您还没有参与竞拍哦", "", true);
				mView.findViewById(R.id.sreach_list).setVisibility(View.GONE);
				pageNumber--;
				break;
			case GET_CHARGE_SUC:
				charge = dataResultForZf.object;
				break;
			case GET_CHARGE_FAIL:
				Toast.makeText(getActivity(), "网络不稳定，请稍后再试", Toast.LENGTH_SHORT)
						.show();
				break;
			}
			return false;
		}
	};
	Handler handler = new Handler(callback);

	private void sendMessage(int what) {
		Message msg = new Message();
		msg.what = what;
		handler.sendMessage(msg);
	}

	// @Click(R.id.main_left_imgbtn)
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.main_left_imgbtn:
			MainActivity.getInstant().fragmentManager.popBackStack();
			break;
		case R.id.to_pay:
			zhifuDialog();
			// Toast.makeText(MainActivity.getInstant(), "zhifu onclick",
			// Toast.LENGTH_SHORT).show();
			break;
		default:
			break;
		}
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		pageNumberTemp = pageNumber;
		pageNumber = 1;
		isRefreash = true;
		getInfoList();
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		isRefreash = false;
		pageNumber++;
		getInfoList();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i("curry", "onResume");
//		biddRecords.biddRecordList.clear();
	}

	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();

	}

	@Override
	public void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		outState.putSerializable("biddRecords", biddRecords);
	}

	private static final int REQUEST_CODE_PAYMENT = 1;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		// super.onActivityResult(requestCode, resultCode, data);
		// 支付页面返回处理
		if (requestCode == REQUEST_CODE_PAYMENT) {
			if (resultCode == Activity.RESULT_OK) {
				String result = data.getExtras().getString("pay_result");
				/*
				 * 处理返回值 "success" - payment succeed "fail" - payment failed
				 * "cancel" - user canceld "invalid" - payment plugin not
				 * installed
				 * 
				 * 如果是银联渠道返回 invalid，调用 UPPayAssistEx.installUPPayPlugin(this);
				 * 安装银联安全支付控件。
				 */
				String errorMsg = data.getExtras().getString("error_msg"); // 错误信息
				if (errorMsg.equals("success")) {
					Toast.makeText(MainActivity.getInstant(), "支付成功",
							Toast.LENGTH_SHORT).show();
				} else {
					Toast.makeText(MainActivity.getInstant(), "支付失败",
							Toast.LENGTH_SHORT).show();
				}

				// Toast.makeText(MainActivity.getInstant(), result,
				// Toast.LENGTH_SHORT).show();
			} else if (resultCode == Activity.RESULT_CANCELED) {
				Toast.makeText(MainActivity.getInstant(), "User canceled",
						Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(MainActivity.getInstant(),
						"An invalid Credential was submitted.",
						Toast.LENGTH_SHORT).show();
			}
			// else if (resultCode == RESULT_EXTRAS_INVALID) {
			// Toast.makeText(MainActivity.getInstant(),
			// "An invalid Credential was submitted.",
			// Toast.LENGTH_SHORT).show();
			// }
		}
	}

	public static AlertDialog alertDialog;
	JSONObject jsonObject;
	Object charge;

	public void zhifuDialog() {
		if (-1 == zhifuPosition) {
			return;
		}
		bindData();
		getCharge();
		alertDialog = new AlertDialog.Builder(MainActivity.getInstant())
				.create();
		alertDialog.show();
		alertDialog.setCanceledOnTouchOutside(false);
		Window window = alertDialog.getWindow();
		window.setContentView(R.layout.zhifu_dialog);
		window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);// ��������n
		TextView sureBtn = (TextView) window.findViewById(R.id.sure_btn);
		final TextView goodsName = (TextView) window
				.findViewById(R.id.goods_name);
		goodsName.setText(biddRecords.biddRecordList.get(zhifuPosition)
				.getTitle());

		final TextView price = (TextView) window
				.findViewById(R.id.info_detail_price);
		double poundage = Double.parseDouble(GlobalData.userInfo.getPoundage()) / 100;
		double cashnu = Double.parseDouble(biddRecords.biddRecordList.get(
				zhifuPosition).getMyPrice());
		double total = cashnu * (Double.parseDouble("1") + poundage);

		String showTotal = priceValidate(total);
		price.setText(showTotal);
		// sureBtn.setBackgroundColor(MainActivity.getInstant().getResources()
		// .getColor(R.color.themeColor));
		sureBtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
				Intent intent = new Intent();
				String packageName = MainActivity.getInstant().getPackageName();
				ComponentName componentName = new ComponentName(packageName,
						packageName + ".wxapi.WXPayEntryActivity");
				intent.setComponent(componentName);
				intent.putExtra(PaymentActivity.EXTRA_CHARGE, charge.toString());
				startActivityForResult(intent, REQUEST_CODE_PAYMENT);
			}
		});
	}

	/*
	 * 价格是否合理
	 */
	private String priceValidate(double price) {
		DecimalFormat df = new DecimalFormat("###.00");
		return df.format(price) + "";
	}

	/**
	 * 封装数据 {"goods_name":"商品名称","goods_price":1111111,
	 * "goods_no":"8d76bac0-db79-4443-aaba-57fce36da87c",
	 * "user_name":"张山","user_no":"501b6bd6-ff54-455f-a99b-2d8b2cf4cfea",
	 * "pay_channel":"wx"}
	 */
	private void bindData() {
		jsonObject = new JSONObject();
		try {
			jsonObject.put("goods_name",
					biddRecords.biddRecordList.get(zhifuPosition).getTitle());
			double poundage = Double.parseDouble(GlobalData.userInfo
					.getPoundage()) / 100;
			double cashnu = Double.parseDouble(biddRecords.biddRecordList.get(
					zhifuPosition).getMyPrice());
			double total = cashnu * (Double.parseDouble("1") + poundage);
			//
			// Integer price =
			// Integer.parseInt(biddRecords.biddRecordList.get(zhifuPosition).getMyPrice())
			// * 100;
			// jsonObject.put("goods_price",price.toString());
			Log.i("curry", "price：" + (total * 100));
			jsonObject.put("goods_price", ((int) total * 100) + "");
			jsonObject.put("goods_no",
					biddRecords.biddRecordList.get(zhifuPosition).getGoodsNo());
			jsonObject.put("user_name", GlobalData.userInfo.getNick());
			jsonObject.put("user_no", GlobalData.userInfo.getUserNo());
			jsonObject.put("pay_channel", "alipay");
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private void getCharge() {
		((MainActivity) getActivity()).cachedThreadPoolMinPriority
				.execute(getChargreRunnable);
	}

	Runnable getChargreRunnable = new Runnable() {
		@Override
		public void run() {
			int what = GET_CHARGE_FAIL;
			dataResultForZf = personalHttpHandler.getChargeData(jsonObject
					.toString());
			// Log.i("curry", "dataResultForZf:" + dataResultForZf.flag);
			// Log.i("curry", "dataResultForZf obj:" + dataResultForZf.object);
			if (dataResultForZf.flag) {
				what = GET_CHARGE_SUC;
			}
			sendMessage(what);
		}
	};
}
